package com.fenghongzhang.lib_core.ui

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.webkit.JavascriptInterface
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.os.EnvironmentCompat
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.fenghongzhang.lib_core.BuildConfig
import com.fenghongzhang.lib_core.R
import com.fenghongzhang.lib_core.base.BaseToolbarActivity
import com.fenghongzhang.lib_core.databinding.ActivityCommonWebBinding
import com.fenghongzhang.lib_core.utils.ARouterUtils
import com.fenghongzhang.lib_core.utils.JLogUtil
import com.fenghongzhang.lib_core.utils.Router
import com.fenghongzhang.lib_core.utils.WebViewUtils
import com.fenghongzhang.lib_core.viewmodel.BlankViewModel
import com.gyf.immersionbar.ktx.immersionBar

import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by ZengCS on 2023/3/9.
 * E-mail:zengcs@vip.qq.com
 * Add:中国成都
 * Desc: CopyMe
 */
@AndroidEntryPoint
@Route(path = Router.Ui.CommonWebActivity)
class CommonWebActivity : BaseToolbarActivity<BlankViewModel, ActivityCommonWebBinding>() {
    override val mViewModel: BlankViewModel by viewModels()
    override val mLayoutResId: Int = R.layout.activity_common_web

    companion object {
        private var mTitle = ""
        private var url = ""
        private var richText = ""
        private var userWebTitle = false
        private var jump4pay = false
        private var exitBack = false
        private var fullScreen = false

        /** 通用跳转 */
        fun jump(
            title: String = "",
            url: String = "",
            richText: String = "",
            useWebTitle: Boolean = false,
            jump4pay: Boolean = false,
            exitBack: Boolean = false,
            fullScreen: Boolean = false
        ) {
            JLogUtil.d("CommonWebActivity called with url = $url")
            this.mTitle = title
            this.url = url
            this.richText = richText
            this.userWebTitle = useWebTitle
            this.jump4pay = jump4pay
            this.exitBack = exitBack
            this.fullScreen = fullScreen
            ARouterUtils.jump(Router.Ui.CommonWebActivity)
        }

        /** 隐私协议 */
        fun jumpPrivacyAgreement(title: String = "隐私协议") {
            this.mTitle = title
          //  this.url = "${BuildConfig.H5_HOST}mobile/agreement?type=1"
            this.fullScreen = false
            this.exitBack = false
            this.userWebTitle = false
            JLogUtil.d("CommonWebActivity called with url = $url")
            ARouterUtils.jump(Router.Ui.CommonWebActivity)
        }

        /** 用户协议 */
        fun jumpUserAgreement(title: String = "用户协议") {
            this.mTitle = title
            this.url = "${BuildConfig.H5_HOST}mobile/agreement?type=2"
            this.fullScreen = false
            this.exitBack = false
            this.userWebTitle = false
            JLogUtil.d("CommonWebActivity called with url = $url")
            ARouterUtils.jump(Router.Ui.CommonWebActivity)
        }

        /** 免责协议 */
        fun jumpPayAgreement(title: String = "免责协议") {
            this.mTitle = title
            this.url = "${BuildConfig.H5_HOST}mobile/agreement?type=3"
            this.fullScreen = false
            this.exitBack = false
            this.userWebTitle = false
            JLogUtil.d("CommonWebActivity called with url = $url")
            ARouterUtils.jump(Router.Ui.CommonWebActivity)
        }
    }

    override fun initStatusBar() {
        immersionBar {
            statusBarDarkFont(true)
            statusBarColor(R.color.white)
        }
    }

    private val mFileSelectorItem by lazy {
//        arrayListOf(
//            CommonBottomItem(1, "图片"),
//            CommonBottomItem(2, "拍照"),
//            CommonBottomItem(3, "文件"),
//            CommonBottomItem(404, "取消")
//        )
    }

    private val mFilePermissions by lazy {
     //  getStorageCompatPermission()
    }
    private val mCameraPermissions by lazy {
        arrayOf(Manifest.permission.CAMERA)
    }

    @SuppressLint("JavascriptInterface")
    override fun initView() {
        super.initView()
        if (fullScreen) {
            mBinding.customToolbar.root.visibility = View.GONE
        }
        WebViewUtils.initWebViewSettings(mBinding.webView, mProgressBar = mBinding.progressBar, onReceiveTitle = {
            if (userWebTitle && mTitle.isEmpty()) {
                //显示网页的title
                mBinding.customToolbar.toolbarTitle.text = it ?: mTitle
            }
        }, openImageChooserActivity = {
            showChooseDialog()
        })
        // 增加Hook方法
        mBinding.webView.addJavascriptInterface(object : Any() {
            /** 打开商品详情 */
            @JavascriptInterface
            fun openGoodsDetail(id: Long) {
               // GoodsDetailActivity.jump(goodsId = id)
            }

            /** 打开订单详情 */
            @JavascriptInterface
            fun openOrderDetail(id: String) {
                //MallOrderDetailActivity.jump(orderCode = id)
            }
        }, "AndroidJs")

        lifecycleScope.launch {
            delay(2000)
            hasPaused = true
        }
    }

    private fun showChooseDialog() {
//        BottomCommonListDialog(mFileSelectorItem, isDarkRowName = true, onChecked = {
//            when (it.key) {
//                1 -> requestPermissions(mFilePermissions) { startFileChooser("image/*") }
//                2 -> requestPermissions(mCameraPermissions) { openCamera() }
//                3 -> requestPermissions(mFilePermissions) { startFileChooser("*/*") }
//            }
//        }, onCancel = {
//            WebViewUtils.mUploadCallbackAboveL?.onReceiveValue(null)
//            WebViewUtils.mUploadMessage?.onReceiveValue(null)
//        }).show(supportFragmentManager)
    }

    private fun startFileChooser(type: String = "*/*") {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = type
        mImageChooserRegister.launch(Intent.createChooser(intent, "Image Chooser"))
    }

    private lateinit var mImageChooserRegister: ActivityResultLauncher<Intent>
    private lateinit var mCameraRegister: ActivityResultLauncher<Intent>

    override fun initListener() {
        mImageChooserRegister =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult(), object : ActivityResultCallback<ActivityResult?> {
                override fun onActivityResult(result: ActivityResult?) {
//                    if (result != null && result.resultCode == Activity.RESULT_OK) {
//                        val intent = result.data
//                        val data = intent?.data
//                        val resultCode = result.resultCode
//                        if (intent != null) {
//                            if (null == WebViewUtils.mUploadMessage && null == WebViewUtils.mUploadCallbackAboveL) return
//                            if (WebViewUtils.mUploadCallbackAboveL != null) {
//                                onActivityResultAboveL(resultCode, intent)
//                            } else if (WebViewUtils.mUploadMessage != null) {
//                                WebViewUtils.mUploadMessage?.onReceiveValue(data)
//                                WebViewUtils.mUploadMessage = null
//                            }
//                        }
//                    } else {
//                        WebViewUtils.mUploadCallbackAboveL?.onReceiveValue(null)
//                    }
                }
            })
        mCameraRegister =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult(), object : ActivityResultCallback<ActivityResult?> {
                override fun onActivityResult(result: ActivityResult?) {
//                    if (result != null && result.resultCode == Activity.RESULT_OK) {
//                        if (null == WebViewUtils.mUploadMessage && null == WebViewUtils.mUploadCallbackAboveL) return
//                        if (WebViewUtils.mUploadCallbackAboveL != null) {
//                            WebViewUtils.mUploadCallbackAboveL?.onReceiveValue(arrayOf(mCameraUri))
//                            WebViewUtils.mUploadCallbackAboveL = null
//                        } else if (WebViewUtils.mUploadMessage != null) {
//                            WebViewUtils.mUploadMessage?.onReceiveValue(mCameraUri)
//                            WebViewUtils.mUploadMessage = null
//                        }
//                    } else {
//                        WebViewUtils.mUploadCallbackAboveL?.onReceiveValue(null)
//                    }
                }
            })



        mBinding.customToolbar.toolbarRightIcon.setOnClickListener {
            if (exitBack) {
                super.onBackPressed()
            }
        }
    }

    override fun initData() {

        if (url.isNotEmpty())
            mBinding.webView.loadUrl(url)
        else if (richText.isNotEmpty())
            mBinding.webView.loadDataWithBaseURL(null, richText, "text/html", "utf-8", null)
    }

    override fun initToolbar(toolbar: Toolbar) {
        // 设置标题
        mBinding.customToolbar.toolbarTitle.text = mTitle
        if (exitBack) {
            mBinding.customToolbar.toolbarRightIcon.visibility = View.VISIBLE
            mBinding.customToolbar.toolbarRightIcon.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.icon_exit))
        } else {
            mBinding.customToolbar.toolbarRightIcon.visibility = View.GONE
        }
    }

    private var hasPaused = false
//    override fun onResume() {
//        super.onResume()
//        if (hasPaused && jump4pay)
//            finish()
//    }

    override fun onBackPressed() {
        if (mBinding.webView.canGoBack() && !jump4pay)
            mBinding.webView.goBack()
        else
            super.onBackPressed()
    }

    private fun requestPermissions(permissions: Array<String>, onGranted: () -> Unit) {
//        RxPermissions(this).requestEachCombined(*permissions)
//            .subscribe { permission ->
//                if (!permission.denied && permission.granted) {
//                    //同意授予
//                    onGranted.invoke()
//                } else if (permission.denied && !permission.granted) {
//                    //拒绝
//                    ToastUtils.showShort(this, "无权限")
//                    WebViewUtils.mUploadCallbackAboveL?.onReceiveValue(null)
//                    WebViewUtils.mUploadMessage?.onReceiveValue(null)
//                } else if (!permission.denied && !permission.granted) {
//                    //未询问,被拒绝
//                    ToastUtils.showShort(this, "无权限，请到设置手动开启")
//                    WebViewUtils.mUploadCallbackAboveL?.onReceiveValue(null)
//                    WebViewUtils.mUploadMessage?.onReceiveValue(null)
//                }
//            }
    }

    private fun onActivityResultAboveL(resultCode: Int, intent: Intent?) {
//        if (WebViewUtils.mUploadCallbackAboveL == null) return
//        var results: Array<Uri?>? = null
//        if (resultCode == Activity.RESULT_OK) {
//            if (intent != null) {
//                val dataString = intent.dataString
//                val clipData = intent.clipData
//                if (clipData != null) {
//                    results = arrayOfNulls(clipData.itemCount)
//                    for (i in 0 until clipData.itemCount) {
//                        val item = clipData.getItemAt(i)
//                        results[i] = item.uri
//                    }
//                }
//                if (dataString != null) results = arrayOf(Uri.parse(dataString))
//            }
//        }
//        WebViewUtils.mUploadCallbackAboveL?.onReceiveValue(results)
//        WebViewUtils.mUploadCallbackAboveL = null
    }

    /**拍照相关*/

    //用于保存拍照图片的uri
    private var mCameraUri: Uri? = null

    // 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
    private var mCameraImagePath: String? = null

    // 是否是Android 10以上手机
    private val isAndroidQ: Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q

    /**
     * 调起相机拍照
     */
    private fun openCamera() {
        val captureIntent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        // 判断是否有相机
        if (captureIntent.resolveActivity(packageManager) != null) {
            var photoFile: File? = null
            var photoUri: Uri? = null
            if (isAndroidQ) {
                // 适配android 10
                photoUri = createImageUri()
            } else {
                try {
                    photoFile = createImageFile()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                if (photoFile != null) {
                    mCameraImagePath = photoFile.getAbsolutePath()
                    photoUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                        FileProvider.getUriForFile(this, "$packageName.JSharefileprovider", photoFile)
                    } else {
                        Uri.fromFile(photoFile)
                    }
                }
            }
            mCameraUri = photoUri
            if (photoUri != null) {
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                mCameraRegister.launch(captureIntent)
                // startActivityForResult(captureIntent, 111)
            }
        }
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private fun createImageUri(): Uri? {
        val status: String = Environment.getExternalStorageState()
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        return if (status == Environment.MEDIA_MOUNTED) {
            contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ContentValues())
        } else {
            contentResolver.insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, ContentValues())
        }
    }

    /**
     * 创建保存图片的文件
     */

    private fun createImageFile(): File? {
        val imageName: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES) ?: return null
        if (!storageDir.exists()) {
            storageDir.mkdir()
        }
        val tempFile = File(storageDir, imageName)
        return if (Environment.MEDIA_MOUNTED != EnvironmentCompat.getStorageState(tempFile)) {
            null
        } else tempFile
    }


}